package my.suveng.alarm.config;

import com.alibaba.ttl.threadpool.TtlExecutors;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import my.suveng.alarm.de.AlarmRejectHandler;
import my.suveng.alarm.de.DingNotify;
import my.suveng.alarm.dependency.Message;
import my.suveng.alarm.dependency.Notify;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author suwenguang
 * @date 2020/11/7 9:02 下午
 * @since 1.0
 */
@Configuration
public class AlarmAutoConfiguration {

    public AlarmAutoConfiguration(AlarmProperties properties) {
        this.properties = properties;
    }

    private final AlarmProperties properties;

    @ConditionalOnMissingBean(value = Notify.class)
    @Bean("dingNotify")
    public Notify dingNotify() {
        return new DingNotify(properties);
    }

    @ConditionalOnMissingBean(name = "alarmPoolExecutorService")
    @Bean("alarmPoolExecutorService")
    public ExecutorService executorService() {
        return TtlExecutors.getTtlExecutorService(new ThreadPoolExecutor(2,
                8,
                60,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(8),
                new ThreadFactoryBuilder().setNameFormat("alarm-pool-%d").build(),
                new AlarmRejectHandler()
        ));
    }
}
